package cn.sytton.taffe.framework.xss;

import cn.hutool.core.collection.CollUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@ConfigurationProperties(prefix = "xss")
public class XssFilterConfig {

    private Boolean enabled = true;
    private List<String> excludes;

    // xss.enabled=true 或者 没有这个属性的时候 才加载这个过滤器
    @Bean
    @ConditionalOnProperty(value = "xss.enabled", havingValue = "true", matchIfMissing = true)
    public FilterRegistrationBean<XssFilter> xssFilterBean(){

        FilterRegistrationBean<XssFilter> bean = new FilterRegistrationBean<>();
        bean.setName("XssFilter");
        bean.setFilter(new XssFilter());
        bean.addUrlPatterns("/*");
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);

        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("excludes", excludes == null ? "" : CollUtil.join(excludes, ","));
        bean.setInitParameters(initParameters);

        return bean;
    }

    public Boolean getEnabled() {
        return enabled;
    }

    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }

    public List<String> getExcludes() {
        return excludes;
    }

    public void setExcludes(List<String> excludes) {
        this.excludes = excludes;
    }

}
